import { Behaviour } from "../gameengine";
import { RectCollider, RectColliderType } from "./RectCollider";

export class ColliderSystem extends Behaviour {


    private rectColliders: RectCollider[] = [];

    public addRectCollider(rectCollider: RectCollider) {
        this.rectColliders.push(rectCollider);
        // console.log('添加了一个矩形碰撞盒')
    }

    public removeRectCollider(rectCollider: RectCollider) {
        const index = this.rectColliders.indexOf(rectCollider);
        if (index != -1) {
            this.rectColliders.splice(index, 1);
        }
    }

    protected onStart() {
        console.log('碰撞系统启动')
    }

    public check(rectA:
        { left: number, right: number, top: number, bottom: number },
        type: RectColliderType

    ) {
        for (let rectB of this.rectColliders) {
            if (rectB.type != type) {
                continue;
            }
            if (rectA.right > rectB.left &&
                rectA.left < rectB.right &&
                rectA.bottom > rectB.top &&
                rectA.top < rectB.bottom
            ) {
                return true;
            }
        }
        return false;
    }


    protected onUpdate(advancedTime: number) {
        if (this.rectColliders.length < 2) {
            // console.log(this.rectColliders)
            return;
        }
        const rectA = this.rectColliders[0];
        const rectB = this.rectColliders[1];

        if (rectA.right > rectB.left &&
            rectA.left < rectB.right &&
            rectA.bottom > rectB.top &&
            rectA.top < rectB.bottom
        ) {
            if (rectA.onColliderStart) {
                rectA.onColliderStart();
            }
            if (rectB.onColliderStart) {
                rectB.onColliderStart();
            }
        } else {
            // console.log('未碰撞')
        }
    }
}